<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2020/07/13 16:09
 * Desc: H5网站登陆/注册
 */
class Model_Api_V2_Member_Wap_Login extends ORM
{

    /**
     * @function 通过手机号/验证码登陆
     */
    public static function login_by_phone($params)
    {
        /**
         * @var $mobile
         * @var $msg_code
         */
        extract($params);
        // 手机号快速登陆验证
        $return = self::sms_quick_login_check($mobile, $msg_code);
        if ($return['status'] == 1) {
            $data = Model_Api_V2_Member_Login::login_init($return['member']);
            $result['status'] = true;
            $result['data'] = $data;
            $result['msg'] = "登录成功";
        } else {
            $result['msg']    = $return['msg'];
            $result['status'] = false;
        }

        return $result;
    }

    //短信快速登录检查
    public static function sms_quick_login_check($phone, $sms_code)
    {

        //动态码为空
        if (!$sms_code) {
            $data = array('msg' => __("error_msg_not_empty"), 'status' => 0);
            return $data;
        }
        $send_code_key = 'login_msgcode_send_code_' . $phone;
        $code_cache = Model_Api_V2_Common::cache('get', $send_code_key);
        //动态码不正确
        if (empty($code_cache) || $sms_code != $code_cache) {
            $data = array('msg' => __("error_msgcode"), 'status' => 0);
            return $data;
        }
        $send_time_key = 'quick_login_send_time'.$phone;
        $send_time = intval(Model_Api_V2_Common::cache('get',$send_time_key));
        //时效检验
        if (time() > ($send_time + 15 * 60)) {
            $data = array('msg' => __("error_overtime_msgcode"), 'status' => 0);
            return $data;
        }
        Model_Api_V2_Common::cache($send_code_key, null);
        Model_Api_V2_Common::cache($send_time_key, null);
        //检测用户是否存在
        $member = Model_Member::member_find($phone);
        if (empty($member)) {
            //如果用户不存在,则自动注册用户
            $mid = Model_Member::auto_reg($phone);
            if($mid)
            {
                $member = Model_Member::member_find($phone);
            }
            else
            {
                $data = array('msg' => __("error_user_noexists"), 'status' => 0);
                return $data;
            }


        }
        $data['status'] = 1;
        $data['member'] = $member;
        return $data;
    }
}
